/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.Util.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-04-25
 */
qui(
    function (require, exports, module) {
        Statistic.Util = $.extend(true, {}, EpgWeb.Util, {
            formatter: {
                download: function (v, o, r) {
                    var htmlArr = [];
//                  if (r.legoProduceFinishedTime !== "1" && Statistic.Util.checkRedoTime(r.addTime)) {
//                      htmlArr.push('<a href="javascript:;" onclick="Statistic.Util.redoReadLog( ' + r.programId + ',\'' + r.addTime + '\'   )">重启制作</a>');
//                    }
                    htmlArr.push('<a href="javascript:;" onclick="Statistic.Util.goToDownload( ' + r.programId + ',\'' + r.channelName + '\' )">下载</a>');
                    htmlArr.push('<a href="javascript:;" onclick="Statistic.Util.openHistory( ' + r.programId + ' )">日志</a>');
                    var result = Statistic.Util.switchWrapSend(r);
                    if (result.length > 0) {
                        htmlArr.push(result);
                    }
                    return htmlArr.join("&nbsp;");
                },
                addTime: function (v, o, r) {
                    return v.substring(0, 10);
                },
                ocrFlag: function (v, o, r) {
                    return v == 0 ? "否" : "是"
                },
                ocrTitleFlag: function (v, o, r) {
                    return v == 0 ? "否" : "是"
                },
                intelligent_insert_time: function (v, o, r) {
                    return v == null ? "" : v;
                },
                enterLegoTime: function (v, r) {
                    return v == null ? "" : v;
                },
                finishedtime: function (v, r) {
                    var rt = Statistic.Config.FINISHED_STATUS[r.legoProduceFinishedTime];
                    if (rt === undefined) {
                        rt = "";
                    }
                    return  rt;
                },
                programMinutes: function (v, o, r) {
                    //   var duration = parseInt((v * 60).toFixed(0));
                    var duration = v;
                    var darArr = [];
                    darArr.push(duration % 60);
                    duration = ( duration - duration % 60) / 60;
                    darArr.push(duration % 60);
                    duration = ( duration - duration % 60) / 60;
                    darArr.push(duration);

                    var retValue = "";
                    switch (darArr.length) {
                        case 3:
                            retValue += darArr[2] <= 0 ? "" : darArr[2] + "时";
                        case 2:
                            retValue += darArr[1] <= 0 ? "" : darArr[1] + "分";
                        case 1:
                            retValue += darArr[0] <= 0 ? "" : darArr[0] + "秒";
                            break;
                    }
                    if (retValue.length == 0) {
                        retValue = "0秒";
                    }
                    return retValue;
                },
                purchase: function (checkValue) {
                    if (checkValue == null)
                        return "";
                    switch (checkValue) {
                        case 0:
                        case -100:
                            return "免费";
                        case 1:
                            return "收费";
                        default:
                            return checkValue + ""
                    }
                },
                publishStatus: function (checkValue) {
                    if (checkValue == null)
                        return "";
                    switch (checkValue) {
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                            return  Statistic.Config.PUBLISH_STATUS[checkValue];
                        default:
                            return checkValue + "";
                    }
                },
                log_type: function (cellvalue, options, rowObject) {
                    var ret = "";
                    var enumNameData = Statistic.Dao.logType();
                    $.each(enumNameData.data, function (index, element) {
                        if (cellvalue == element.key) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret;
                },
                log_descr: function (cellvalue, options, rowObject) {
                    var ret = cellvalue;
                    if (rowObject.type == 107 || rowObject.type == 108) {
                        ret = Statistic.Util.decodeDescription(cellvalue)
                    }
                    return  ret;
                },
                dataMode: function (cellvalue, options, rowObject) {
                    var ret = "";
                    switch (cellvalue) {
                        case Statistic.Config.STATISTIC_DATA_MODE.original:
                            ret = "纯净版";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_new:
                            ret = "新建包装版-分片";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_not_made:
                            ret = "包装覆盖未制作-分片";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_made:
                            ret = "包装覆盖已制作-分片";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.wrap_new:
                            ret = "新建包装版";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.wrap_not_made:
                            ret = "包装覆盖未制作";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.wrap_made:
                            ret = "包装覆盖已制作";
                            break;
                        default :
                            ret = "旧数据类型" + cellvalue;
                            break;
                    }
                    return ret;
                }
            },
            goToDownload: function (id, channelName) {
                var legoData = Statistic.Dao.getDataByName("legoChannelId");
                if (legoData == null) {
                    EpgWeb.Plugin.showTips({type: "error", content: "lego接口异常"})
                    return;
                }
                var channelData = null;
                $.each(legoData.data, function (i, element) {
                    if (element.name == channelName) {
                        channelData = element;
                        return true;
                    }
                })
                Statistic.Dao.doAuthData({
                    url: Statistic.Constant.auth_base_url + channelData.id,
                    doError: function () {
                        EpgWeb.Plugin.showTips({type: "error", content: "用户没有 " + channelName + " 下载权限"});
                    },
                    doSuccess: function () {
                        window.open('http://lego.iqiyi.com/material/download?id=' + id + '&entityType=0', '_target')
//  + '<a data-url-id='+r.programId+' style="display:none" target="_new" href="http://lego.iqiyi.com/material/download?id=' + r.programId + '&entityType=0">下载</a>'
                        // $("a[data-url-id="+id+"]").click();
                    }
                })
            },
            checkRedoTime: function (addTime) {
                var currentTime = new Date();
                var queryTime = new Date(addTime.replace(/-/g, "/"));
                return  ( queryTime.getTime() >= currentTime.getTime() - 3 * 86400000 )
            },

            doFragmentPublishProcess: function (programId, addTime) {
                var process = new Statistic.Process({regKey: "" + programId });
                var node3 = {key: "queryList2", nextKey: "sendPublish", root: true}
                var node5 = {key: "sendPublish"}
                //node3
                process.addProcessTree(node3);
                process.addOrderFunObj(node3.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "108", "/dot/append2"))
                //node5
                process.addProcessTree(node5);
                process.addOrderFunObj(node5.key, Statistic.Dao.makeOptionsDadianPublish("queryList2"))
                process.startProcess();
            },
            doIntegralNewProcess: function (programId, addTime) {
                this.redoPublishProcess(programId, addTime);
            },
            doIntegralUnMadeProcess: function (programId, mode, addTime) {
                console.log("mode:" + mode);
                var modeStr = "";
                var hintMsg = "";
                if (mode == 1) {
                    modeStr = "仅包装发布";
                    hintMsg = "是否确认仅包装发布"
                } else if (mode == 2) {
                    modeStr = "覆盖包装发布";
                    hintMsg = "是否确认覆盖包装发布"
                }
                var handler = function (resultData) {
                    Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.selectSendMode,
                        {
                            user: auth.baseInfo.authInfo.email,
                            mode: modeStr
                        },
                        resultData, "");
                }
                SystemDialog.queryConfirm(hintMsg, function (flag) {
                    if (flag == true) {
                        if (mode == 2) {
                            Statistic.Util.redoPublishProcess(programId, addTime, handler,{"reTranscodeConfirm":1})
                        } else {
                            Statistic.Util.doDirectPublishProcess(programId, addTime, handler);
                        }
                    }
                })
            },
            doIntegralMadeProcess: function (programId, addTime) {
                this.redoPublishProcess(programId, addTime);
            },
            redoPublishProcess: function (programId, addTime, handler ,overrideData) {
                var process = new Statistic.Process({regKey: "" + programId, handler: handler  });
                //  var node6 = {key: "checkSendLego", nextKey: "checkLegoVideoData", root: true};
                var node1 = {key: "checkLegoVideoData", nextKey: "queryList1", root: true};
                var node2 = {key: "queryList1", nextKey: "queryList2"}
                var node3 = {key: "queryList2", nextKey: "sendLegoRemake"}
                var node4 = {key: "sendLegoRemake", nextKey: "sendPublish"}
                var node5 = {key: "sendPublish"}
                // node1;
                process.addProcessTree(node1);
                process.addOrderFunObj(node1.key, Statistic.Dao.makeOptionsCheckLegoVideoData(programId));
                // node2;
                process.addProcessTree(node2);
                process.addOrderFunObj(node2.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "122"))
                //node3
                process.addProcessTree(node3);
                process.addOrderFunObj(node3.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "107,108", "/dot/append2"))
                //node4
                process.addProcessTree(node4);
                process.addOrderFunObj(node4.key, Statistic.Dao.makeOptionsGNotifyLegoRemake("queryList1",overrideData))
                //node5
                process.addProcessTree(node5);
                process.addOrderFunObj(node5.key, Statistic.Dao.makeOptionsDadianPublish("queryList2",overrideData))
                process.startProcess();
            },

            doDirectPublishProcess: function (programId, addTime, handler) {
                var process = new Statistic.Process({regKey: "" + programId, handler: handler});
                var node2 = {key: "queryList1", nextKey: "queryList2", root: true}
                var node3 = {key: "queryList2", nextKey: "sendLegoRemake"}
                var node4 = {key: "sendLegoRemake", nextKey: "sendPublish"}
                var node5 = {key: "sendPublish"}
                // node2;
                process.addProcessTree(node2);
                process.addOrderFunObj(node2.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "122"))
                //node3
                process.addProcessTree(node3);
                process.addOrderFunObj(node3.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "107,108", "/dot/append2"))
                //node4
                process.addProcessTree(node4);
                process.addOrderFunObj(node4.key, Statistic.Dao.makeOptionsGNotifyLegoRemake("queryList1"))
                //node5
                process.addProcessTree(node5);
                process.addOrderFunObj(node5.key, Statistic.Dao.makeOptionsDadianPublish("queryList2"))
                process.startProcess();
            },
            decodeSendLegoData:function(sendData,overrideData){
                var requestData = JSON.parse(sendData.request);
                var toLegoData =  JSON.parse(requestData.params.data);
                toLegoData = $.extend({},toLegoData,overrideData);
                requestData.params.data = JSON.stringify(toLegoData);
                sendData.request = JSON.stringify(requestData);
                return sendData;
            },
            decodeDescription: function (description) {
                var elementArr = description.split("|");
                var newArr = [];
                if (elementArr.length == 2) {
                    newArr.push(elementArr.shift());
                } else if (elementArr.length >= 3) {
                    newArr.push(elementArr.shift());
                    newArr.push(elementArr.shift());
                }
                var jsonObj = JSON.parse(elementArr.join("|"));
                var list = JSON.parse(jsonObj.list);
                if (list.length > 2) {
                    var newFold = [];
                    var nodeStart = -100;
                    var nodeEnd = -100;
                    var curIndex = 0;
                    $.each(list, function (i, element) {
                        curIndex = element;
                        if (curIndex > nodeEnd + 1) {
                            if (nodeStart >= 0) {
                                newFold.push({ start: nodeStart, end: nodeEnd});
                            }
                            nodeStart = curIndex;
                            nodeEnd = curIndex;
                        } else if (curIndex == nodeEnd + 1) {
                            nodeEnd = curIndex;
                        }
                    })
                    if (nodeEnd >= nodeStart) {
                        newFold.push({ start: nodeStart, end: nodeEnd});
                    }
                    jsonObj.list = newFold;
                }
                newArr.push(JSON.stringify(jsonObj));
                return newArr.join("|");
            },
            episodeLogSubmit: function (programId, type, params, response, plusMsg) {
                var submitData = {
                    programId: programId,
                    type: type,
                    user: auth.baseInfo.authInfo.email,
                    descr: JSON.stringify(response) + ( plusMsg == null ? "" : "|" + plusMsg) + "|" + JSON.stringify(params) };
                Statistic.Util.doSubmitEpisodeLogEntity(submitData);
                if(type == Statistic.Config.VOD_LOG_TYPE.sendWrapDataToLego_suc){
                    if(null == params.paramType){
                        console.log("old data has no isAppendFragementFlag");
                        return ;
                    }else{
                        var tempData = {
                            success: true,
                            funcType: "create_video",
                            sendData: JSON.stringify(params),
                            plusMsg: plusMsg,
                            response: response,
                            programId: programId,
                            serverIp: params.serverIp,
                            paramType: params.paramType
                        }
                        EpgWeb.PingBack.doQuickSend(tempData);
                        tempData = null;
                    }
                }
            },
            doSubmitEpisodeLogEntity: function (submitLogData) {
                Statistic.Dao.submitEpisodeLogEntity(submitLogData, function (data) {
                        if (data == null || data.code != "A00000") {
                            console.warn("SubmitEpisodeLogEntity error");
                        } else {
                            console.log("SubmitEpisodeLogEntity suc");
                        }
                    }
                )
            },
            openHistory: function (entityId) {
                $("#vodEpisodeLogDiv").dialog("open");
                $('#logList').jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {paramsObj: JSON.stringify({ EQL_programId: entityId})}
                }).trigger('reloadGrid');
            },
            buildTH: function (dataArr) {
                var retValue = [];
                $.each(dataArr, function (i, element) {
                    retValue.push("<td>" + element + "</td>");
                });
                return "<tr>" + retValue.join("") + "</tr>";
            },
            buildTD: function (object, keyArr) {
                var retValue = [];
                $.each(keyArr, function (index, element) {
                    var configData = Statistic.Config.TABLE_COLMODEL_CONFIG[element];
                    if (configData.formatter != null) {
                        retValue.push("<td>" + configData.formatter(object[configData.name], null, object) + "</td>");
                    } else {
                        retValue.push("<td>" + object[configData.name] + "</td>");
                    }
                });
                return "<tr>" + retValue.join("") + "</tr>";
            },
            // 乐高 重转 js 判断
            isAvailableForReTranscode: function (data) {
                var isPurchase = data.isPurchase;
                var freeTypeStatus = data.freeTypeStatus;
                var canBeTranscode = data.canBeTranscode;
                var isMainChannel = data.isMainChannel;
                //重转处理完成 并处于待划价时， 置灰重转链接
                if (isPurchase == "1" && freeTypeStatus == "3") {
                    return false;
                }
                // 是主频道并可以重转时 重转可用
                if (canBeTranscode && (isMainChannel == 1)) {
                    return true;
                }
                return false;
            },
            // 乐高 非编 js 判断
            isAvailableForNonlinear: function (data) {
                var isPurchase = data.isPurchase;
                var freeTypeStatus = data.freeTypeStatus;
                var canBeMake = data.canBeMake;
                var isMainChannel = data.isMainChannel;
                //重转处理完成 并处于待划价时， 置灰非编链接
                if (isPurchase == "1" && freeTypeStatus == "3") {
                    return false;
                }
                // 是主频道并可以重转时 重转可用
                if (canBeMake && (isMainChannel == 1)) {
                    return true;
                }
                return false;
            },
            switchWrapSend: function (statisticData) {
                var ret = "";
                switch (statisticData.dataMode) {
                    case 0:
                        break;
//                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_new:
////                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_not_made:
////                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_made:
//                        ret = '<a href="javascript:;" onclick="Statistic.Util.doFragmentPublishProcess( ' + statisticData.programId + ',\'' + statisticData.addTime + '\'   )">分片包装发布</a>'
//                        break;
//                    case Statistic.Config.STATISTIC_DATA_MODE.wrap_new:
//                        ret = '<a href="javascript:;" onclick="Statistic.Util.doIntegralNewProcess( ' + statisticData.programId + ',\'' + statisticData.addTime + '\'   )">新建包装发布</a>'
//                        break;
                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_not_made:
                    case Statistic.Config.STATISTIC_DATA_MODE.wrap_not_made:
                        ret = '<a href="javascript:;" onclick="Statistic.Util.doIntegralUnMadeProcess( ' + statisticData.programId + "," + 2 + ',\'' + statisticData.addTime + '\'   )">覆盖包装发布</a>&nbsp;' +
                            '<a href="javascript:;" onclick="Statistic.Util.doIntegralUnMadeProcess( ' + statisticData.programId + "," + 1 + ',\'' + statisticData.addTime + '\'   )">仅包装发布</a>'
                        break;
                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_made:
                    case Statistic.Config.STATISTIC_DATA_MODE.wrap_made:
                        ret = '<a href="javascript:;" onclick="Statistic.Util.doIntegralMadeProcess( ' + statisticData.programId + ',\'' + statisticData.addTime + '\'   )">覆盖包装发布</a>'
                        break;
                }
                return ret;
            }
        })
    }
);